<?php

namespace Beerus\Modules\DecoCompany\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DecoCompany\Actions\AddSubsidiary;
use Beerus\Modules\DecoCompany\Actions\CancelAuth;
use Beerus\Modules\DecoCompany\Actions\DelSubsidiary;
use Beerus\Modules\DecoCompany\Actions\SetBudgetTag;
use Beerus\Modules\DecoCompany\Actions\SetGroup;
use Doraemon\cache\Queue;
use Doraemon\model\Article;
use Doraemon\model\CommunityMcn\GoodsRecommender as mGoodsRecommender;
use Doraemon\model\DecoCompany\DecoCompanyServiceLog;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DecoCompanyCertificate;
use Doraemon\model\DecoCompanyCombo;
use Doraemon\model\DecoCompanyEffect;
use Doraemon\model\DecoCompanyIssue;
use Doraemon\model\DecoCompanyIssueAnswer;
use Doraemon\model\DecoCompanyReservation;
use Doraemon\model\Member;
use Doraemon\model\Member as mMember;
use Doraemon\service\DecoCompany\Certificate;
use Doraemon\service\DecoCompany\DecoCompany as sDecoCompany;
use Doraemon\service\DecoCompany\DecoCompanyGroup as sDecoCompanyGroup;
use Doraemon\service\DecoCompany\DecoCompanyService;
use Doraemon\service\DecoCompany\Schedule;
use Doraemon\service\DecoCompany\Shop;
use Doraemon\service\es\EsDecoCompany;
use Doraemon\service\User;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\ParamsCheck;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Doraemon\model\DecoCompany;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Illuminate\Support\MessageBag;
use Doraemon\service\DecoCompany\Reservation as sReservation;
use Medoo\Medoo;
use Beerus\Modules\DecoCompany\Actions\shortRecommendText;

class IndexController
{
	const AUDIT_TEXT = [
		DecoCompanyCertificate::AUDIT_PASS => '通过',
		DecoCompanyCertificate::AUDIT_FAIL => '不通过'
	];

	const PAGE_SIZE = 15;

	const DEFAULT_IMG = 'http://img.hhz1.cn/Op-imageShow/5472d20gy0gy0OI00qwa4rb?iv=1';

    // 列表
    public function index(Request $request,Content $content)
    {
        Admin::script(self::setScript());
        $params = $request->all();
        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
	    if (!empty($params['uid'])) {
		    $condition['uid'] = $params['uid'];
	    }

	    if (!empty($params['nick'])) {
		    $uid = User::getUidByNick($params['nick']);
		    $condition['uid'] = $uid;
	    }

        if (!empty($params['have_recommend_text'])) {
            if (count($params['have_recommend_text']) < 2){
                if ($params['have_recommend_text'][0] == 1){
                    $condition['short_recommend_text[!]'] = "";
                }elseif ($params['have_recommend_text'][0] == 9){
                    $condition['short_recommend_text'] = "";
                }
            }
        }

	    if (empty($params['auth_status'])) {
	    	$condition['auth_status'] = DecoCompany::AUTH_STATUS_SUCCESS;
	    } else {
		    $condition['auth_status'] = $params['auth_status'];
	    }
        if (!empty($params['main_area_name'])) {
            $condition['main_area_name'] = $params['main_area_name'];
        }

        if (!empty($params['ability_tag'])) {
            $ability_tag = explode(' ', $params['ability_tag']);
            if ($ability_tag) {
                $condition["OR"] = [
                    "ability_tag_al[~]" => $ability_tag,
                    "ability_tag_op[~]" => $ability_tag
                ];
            }
        }

        if (isset($params['group_type']) && $params['group_type'] != "") {
            $condition['group_type'] = $params['group_type'];
        }

	    $total = DecoCompany::count($condition);

	    $lists = [];
        if ($total) {
	        $condition['ORDER'] = ['id' => 'DESC'];
	        $condition['LIMIT'] = [
		        ($page - 1) * $page_size,
		        $page_size
	        ];

	        $lists = DecoCompany::select('*', $condition);
	        $user_ids = array_column($lists, 'uid');
	        $member_info = Member::getUsers($user_ids);

	        // 套餐数据
	        $split_uid = implode(',', $user_ids);
	        $sql = "select uid, COUNT(1) as num from hhz_deco_company_combo where uid IN (". $split_uid .") AND check_status = 2 AND combo_status = 1 group by uid";
	        $combo_info = DecoCompanyCombo::query($sql)->fetchAll();
	        $group_combo = [];
	        foreach ($combo_info as $item) {
	        	$group_combo[$item['uid']] = $item['num'];
	        }

	        // 整屋
	        $article_status = implode(',', Article::$base_normal_visible_status);
	        $sql = "select uid, COUNT(1) as num from hhz_article where uid IN (". $split_uid .") AND status IN (". $article_status .") group by uid";
	        $article_info = Article::query($sql);
	        $group_article = [];
	        foreach ($article_info as $item) {
		        $group_article[$item['uid']] = $item['num'];
	        }

	        // 留咨电话信息
	        //$sql = "select deco_company_uid, COUNT(1) as num from hhz_deco_company_reservation where uid IN (". $split_uid .") AND status = 1 group by uid";
			$reservation_info = DecoCompanyReservation::select(['deco_company_uid', 'encrypt_user_phone'], [
				'deco_company_uid' => $user_ids,
				'data_status' => DecoCompanyReservation::STATUS_NORMAL
			]);

			$group_reservation = [];
			if (!empty($reservation_info)) {
                foreach ($reservation_info as $item) {
                    $group_reservation[$item['deco_company_uid']][] = $item['encrypt_user_phone'];
                }
            }

			// 效果图案例数
	        $sql = "select uid, COUNT(1) as num from decoration_company_effect where uid IN (". $split_uid .") AND effect_status = ". DecoCompanyEffect::STATUS_NORMAL ." group by uid";
	        $effect_info = DecoCompanyEffect::query($sql);
	        $group_effect = [];
	        foreach ($effect_info as $item) {
		        $group_effect[$item['uid']] = $item['num'];
	        }
	        //获取装修公司下的所有城市
            $city_list = DecoCompany::select(['main_area_name' => Medoo::raw('DISTINCT(main_area_name)')], [
            	'auth_status' => DecoCompany::AUTH_STATUS_SUCCESS,
	            'main_area_name[!]' => ''
            ]);
            $city_list = array_column($city_list, 'main_area_name');
	        $cityArr = [];
	        foreach ($city_list as $item) {
                $cityArr[$item] = $item;
            }
	        foreach ($lists as &$item) {
		        $reservation = $distinct_reservation = 0;
	        	if (!empty($group_reservation[$item['uid']])) {
			        $reservation = count($group_reservation[$item['uid']]);
			        $distinct_reservation = count(array_unique($group_reservation[$item['uid']]));
		        }
	        	$item['user_type'] = Member::$typeDesc[$member_info[$item['uid']]['type']];
		        $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
		        $item['combo'] = empty($group_combo[$item['uid']]) ? 0 : (int)$group_combo[$item['uid']];
		        $item['article'] = empty($group_article[$item['uid']]) ? 0 : (int)$group_article[$item['uid']];
		        $item['reservation'] = $reservation;
		        $item['distinct_reservation'] = $distinct_reservation;
		        $item['effect'] = empty($group_effect[$item['uid']]) ? 0 : (int)$group_effect[$item['uid']];
		        $item['is_recommend_reason'] = empty($item['recommend_reason']) ? "无" : "有";
		        $item['score_detail'] = sDecoCompany::FormatScoreDetail($item['uid']);
                // 增加运营自定义分数
                $item['score_detail'][] = [
                    'scoreName' => '运营自定义分数',
                    'result' => '',
                    'score' => '<div class="custom-score-box">
                                    <div class="col-xs-2" style="padding-left: 0">
                                        <input type="text" value="'.$item['custom_score'].'" class="form-control custom-score" style="" />
                                        <input type="text" class="deco-uid" value="'.$item['uid'].'" style="display: none" />
                                    </div>
                                    <a class="btn btn-success custom-score-btn" style="cursor: pointer"> 提交</a>
                                </div>'
                ];
		        $item['short_recommend_text'] = \Doraemon\service\DecoCompany\DecoCompany::formatShortRecommend($item['short_recommend_text']);
	        }
	        unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel,$cityArr) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
	            $grid->filter(function (Grid\Filter $filter) use($cityArr){
		            $filter->disableIdFilter();
		            $filter->column(1 / 4, function ($filter) {
			            $filter->equal('uid', '用户UID')->placeholder('请输入uid');
		            });
		            $filter->column(1 / 4, function ($filter) {
			            $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
		            });
                    $filter->column(1 / 4, function ($filter) use($cityArr) {
                        $filter->equal('main_area_name', '服务城市')->select($cityArr);
                    });
                    $filter->column(1 / 4, function ($filter) {
                        $filter->equal('ability_tag', '能力标签')->placeholder('多个标签以空格分隔');
                    });
                    $filter->column(1 / 4, function ($filter) {
                        $filter->equal('group_type', '集团公司')->select(DecoCompany::GROUP_TYPE_DESC);
                    });
		            $filter->column(1 / 2, function ($filter) {
                        $filter->equal('have_recommend_text', '是否设置了一句话推荐')->checkbox([
                            1 => '有',
                            9 => '没有',
                        ]);
		            });
		            $filter->expand();
	            });

                $grid->column('id', 'ID');
                $grid->column('uid', 'UID')->copyable();
	            $grid->column('nick', '公司昵称')->copyable();
                $grid->column('main_area_name', '服务城市');
                $grid->column('group_type', '集团公司')->using(DecoCompany::GROUP_TYPE_DESC);
                $grid->column('combo', '套餐数');
                $grid->column('article', '整屋案例数');
	            $grid->column('effect', '效果图案例数');
                $grid->column('auth_time', '认证时间')->display(function () {
	                if (empty($this->auth_time)) {
	                	return '-';
	                } else {
	                	return date('Y-m-d H:i:s', $this->auth_time);
	                }
                });
	            $grid->column('consulting', '收到的留资电话数（去重/不去重）') ->display(function () {
	            	return $this->distinct_reservation .' / '. $this->reservation;
	            });
                Admin::style('.column-ability_tag .label-default {display: inline-block;}');
                $grid->column("ability_tag", '能力标签')->display(function () {
                    return array_filter(array_merge(explode(',', $this->ability_tag_al), explode(',', $this->ability_tag_op)));
                })->label('default')->style("width:50px;");
	            $grid->column('user_type', '当前用户身份');
                $grid->column('short_recommend_text', '一句话推荐文案')->display(function () {
                    return $this->short_recommend_text ;
                });
//	            $grid->column('sort', '列表排序')->modal('编辑列表排序', function () {
//                    $form = new Form();
//                    $form->disableReset();
//                    $form->disableSubmit();
//                    $form->hidden('id')->default($this->id);
//                    $form->hidden('filed')->default('列表排序');
//                    $form->number('sort', '列表排序')->min(1)->default($this->sort)->required();
//                    $form->html('<div class="modal-submit"><button type="button" class="btn btn-primary">提交</button></div>')->plain();
//                    Admin::style('.modal-submit{text-align: right;padding: 0 23%;}');
//
//                    return $form;
//                });
                $grid->column('score', '排序分数')->modal('排序分数明细', function ($model) {
                    return new Table(['评分项', '结果', '得分'], $this->score_detail);
                });
	            $grid->column('is_recommend_reason', '推荐理由')->modal('编辑推荐理由', function () {
                    $form = new Form();
                    $form->disableReset();
                    $form->disableSubmit();
                    $form->hidden('id')->default($this->id);
                    $form->hidden('filed')->default('推荐理由');
                    $form->text('recommend_reason', '推荐理由')->default($this->recommend_reason)->attribute('maxlength', 20);
                    $form->html('<div class="modal-submit"><button type="button" class="btn btn-primary">提交</button></div>')->plain();
                    Admin::style('.modal-submit{text-align: right;padding: 0 23%;}');

	                return $form;
                });
	            $grid->column('is_show', '当前是否展示在列表')->switchToggle([
		            'on' => [
			            'value' => DecoCompany::SHOW_TRUE,
			            'text' => '是'
		            ],
		            'off' => [
			            'value' => DecoCompany::SHOW_FALSE,
			            'text' => '否'
		            ]
	            ]);
	            $grid->setActionClass(DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
	                //$actions->disableView();

	                $actions->add(new CancelAuth);
	                $actions->add(new SetBudgetTag());
	                $actions->add(new SetGroup());
	                $actions->add(new shortRecommendText);
                });
            });

        $tab = new Tab();
        $tab->add('装修公司列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('装修公司列表')
            ->description(' ')
            ->breadcrumb(['text' => '装修公司列表']);
    }

    public static function setScript() {
        return <<<SCRIPT
            $('.modal-submit button').on('click',function(e){
                e.preventDefault();
                var form = $(this).parents('form');
                var inputList = form.serializeArray();
                var filedValue = "";
                for (var i = 0; i < inputList.length; i++) {
                    if (inputList[i].name == "filed") {
                        filedValue = inputList[i].value;
                        break;
                    }
                }
                layer.confirm('确定要编辑' + filedValue + '么？', {
                    btn: ['确定', '取消']
                }, function (index) {
                    layer.close(index);
                    $.post("/admin/DecoCompany/companies/gridEdit", form.serialize(), function(data){
                        layer.msg(data.message);
                        if (data.status) {
                            setTimeout(function () {
                                parent.window.location.reload();
                            }, 200);
                        }
                    });
                });
            });
            
            // 分数编辑
            $('.custom-score-btn').on('click',function(e){
                let params = {
                    uid:$(this).parent().find('.deco-uid').val(),
                    custom_score:$(this).parent().find('.custom-score').val(),
                };
                layer.confirm('确定要编辑修改自定义分数么？', {
                    btn: ['确定', '取消']
                }, function (index) {
                    layer.close(index);
                    $.post("/admin/DecoCompany/companies/scoreEdit", params, function(data){
                        layer.msg(data.message);
                        if (data.status) {
                            setTimeout(function () {
                                parent.window.location.reload();
                            }, 200);
                        }
                    });
                });
            });
        SCRIPT;
    }

    public function show(Request $request, $id)
    {
        $params = $request->all();

	    $list = [
		    'lishuai',
            'lijiaqi1',
	    ];
	    if (HhzEnv::isProduction() && !in_array(Admin::user()->username, $list)) {
		    return response()->json([
			    'status' => false,
			    'message' => '您没有权限操作,可操作人员名单：'. implode('、', $list),
		    ]);
	    }

		$is_show = $params['is_show'] == 'on'? 1: 0;

		$info = DecoCompany::get('*', [
			'id' => $id
		]);
		$user = Member::getOne($info['uid']);

		if ($user['type'] == Member::USER_COMMON && $is_show) {
			return response()->json([
				'status' => false,
				'message' => "修改失败，用户身份非装修公司！",
			]);
		}

        $result = DecoCompany::updateInfoById($id, [
            'is_show' => $is_show
        ]);

	    sDecoCompany::esSync($info['uid'], [
		    'is_show' => $is_show,
		    'main_area_name' => $info['main_area_name'],
		    'sort' => $info['sort'],
		    'from' => DecoCompanyServiceLog::FROM_MANAGE
	    ]);

//        if ($is_show) {
//	        Queue::insertQueue('/queue/Decocompany/EsSync',[
//		        'uid' => $info['uid'],
//		        'auth_status' => DecoCompanyAuth::AUTH_STATUS_SUCCESS,
//	        ], 'hzQDoraemon');
//        } else {
//	        EsDecoCompany::delete($info['uid']);
//        }

        if ($result){
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

    public function detail(Request $request, Content $content, $id, $tab_id = 1)
    {
	    $tab = new Tab();
	    $tab->addLink('基础信息', '/admin/DecoCompany/companies/' . $id . '/1', $tab_id == 1);
	    $tab->addLink('常见问题及答案内容', '/admin/DecoCompany/companies/' . $id . '/2', $tab_id == 2);
	    $tab->addLink('留咨电话列表', '/admin/DecoCompany/companies/' . $id . '/3', $tab_id == 3);
	    $tab->addLink('线下店内容', '/admin/DecoCompany/companies/' . $id . '/4', $tab_id == 4);
	    $tab->addLink('中装协五星认证', '/admin/DecoCompany/companies/' . $id . '/5', $tab_id == 5);
	    $tab->addLink('集团公司维护', '/admin/DecoCompany/companies/' . $id . '/6', $tab_id == 6);

        $content->header('装修公司信息详情')
            ->breadcrumb([
                'text' => '装修公司列表',
                'url' => route('company.list'),
            ], ['text' => '装修公司信息详情'])
            ->body($tab);

        switch ($tab_id) {
            case 1:
                $content = $this->basic($content, $id);
                break;
            case 2:
                $content = $this->questions($content, $id);
                break;
            case 3:
                $content = $this->reservation($content, $id, $request);
                break;
            case 4:
                $content = $this->shops($content, $id);
                break;
            case 5:
                $content = $this->cbda5S($content, $id);
                break;
            case 6:
                $content = $this->groupList($content, $id);
                break;
        }

	    return $content;
    }

    public function basic(Content $content, $id)
    {
    	$data = DecoCompany::get('*', [
    		'id' => $id
	    ]);
    	$data['nick'] = Member::getNickByUid($data['uid']);
    	$combo = DecoCompanyCombo::count([
    		'uid' => $data['uid'],
    		'combo_status' => DecoCompanyCombo::STATUS_NORMAL,
		    'check_status' => DecoCompanyCombo::CHECK_PASSED
	    ]);
    	$data['combo'] = empty($combo) ? 0 : (int)$combo;
    	$article = Article::count([
			'uid' => $data['uid'],
		    'status' => Article::$base_normal_visible_status
	    ]);
    	$data['article'] = empty($article) ? 0 : (int)$article;
    	$effect = DecoCompanyEffect::count([
    		'uid' => $data['uid'],
    		'effect_status' => DecoCompanyEffect::STATUS_NORMAL
	    ]);
    	$data['effect'] = empty($effect) ? 0 : (int)$effect;
    	$data['auth_time'] = empty($data['auth_time']) ? '' : date('Y-m-d H:i:s', $data['auth_time']);
	    $form = new Form($data);
	    $form->hidden('id');
	    $form->hidden('tab_id');
	    $form->display('uid', '装修公司UID')->setWidth(3, 2);
	    $form->display('nick', '装修公司昵称')->setWidth(3, 2);
	    $form->display('combo', '套餐数')->setWidth(3, 2);
	    $form->display('article', '整屋案例数')->setWidth(3, 2);
	    $form->display('effect', '效果图案例数')->setWidth(3, 2);
	    $form->display('auth_time', '认证时间')->setWidth(3, 2);
	    $states = [
		    'on'  => ['value' => 1, 'text' => '是'],
		    'off' => ['value' => 0, 'text' => '否']
	    ];
	    $form->switch('is_show', '是否展示在装修公司列表')->states($states);
        $form->display('video_id', '主页宣传视频')->with(function ($value) {
            if ($value) {
                $videoInfo = sVideos::getVideoCoverInfoById($value);
                return "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}'></video>";
            } else {
                return "";
            }
        })->setWidth(4);
        $form->display('homepage_header_pic', '主页宣传图片')->with(function ($value) {
            $homepage_header_pic = explode(',', $value);
            $html = '';
            if ($homepage_header_pic) {
                foreach ($homepage_header_pic as $pic) {
                    $pic_url = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $pic, ImgUrl::IMAGE_SIZE_O_500);
                    $html .= "<span style='display: inline-block;width: 205px;margin: 5px 5px;cursor: pointer;'><img class='xc-img' style='width:100%;' src='{$pic_url}' /></span>";
                }
            }
            return $html;
        });
        $form->html('<div id="img-modal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" 
	aria-labelledby="myLargeModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="max-width:90%;">
	  <div class="modal-content"></div>
	</div>
</div>');
        Admin::script($this->imgScript());

	    $form->disableReset();
	    $form->disableSubmit();

	    $form->confirm('确认操作「是否展示在装修公司列表」数据吗？');

	    $form->action('/admin/DecoCompany/companies/saveBasic');
	    return $content->row($form->render());
    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.xc-img').click(function(){
                var img_html = $(this).prop("outerHTML");
                $('#img-modal .modal-content').html(img_html);
                $('#img-modal').modal('show');
                // 点击隐藏 modal
                $('#img-modal .modal-content img').click(function(){
                    $('#img-modal').modal('hide');
                })
            });
SCRIPT;
    }

	/**
	 * 常见问题及答案内容
	 * @param $id
	 * @return string
	 */
    public function questions(Content $content, $id)
    {
	    $data = DecoCompany::get('*', [
		    'id' => $id
	    ]);
	    $uid = $data['uid'];
	    $issue_list = DecoCompanyIssue::getAllIssueByUid($uid);
	    $total = count($issue_list);
	    $lists = [];
	    if ($issue_list) {
		    foreach ($issue_list as $item) {
			    $row = [];
			    $row['id'] = $item['id'];
			    $row['title'] = $item['issue_title'];
			    $row['example'] = $item['example'];
			    $row['answer'] = DecoCompanyIssueAnswer::getIssueAnswer($item['id'], $uid);
			    $row['is_default'] = $item['is_default'];
			    $row['add_time'] = empty($item['add_time']) ? '-' : date('Y-m-d H:i:s', $item['add_time']);
			    $row['edit_time'] = empty($item['edit_time']) ? '-' : date('Y-m-d H:i:s', $item['edit_time']);
			    $lists[] = $row;
		    }
	    }

	    $gridModel = new pGridDataModel($lists, $total, [
		    'perPage' => self::PAGE_SIZE
	    ]);
	    $gridList = Admin::grid(
		    $gridModel,
		    function (Grid $grid) use ($gridModel) {
			    $grid->paginate($gridModel->getPerPage());
			    $grid->disableExport();
			    $grid->disableCreateButton();
			    $grid->disableActions();
			    $grid->disableFilter();
			    $grid->disableRowSelector();

			    $grid->column('id', 'ID');
			    $grid->column('title', '问题标题');
			    $grid->column('answer', '回答');
			    $grid->column('example', '参考示例');
			    $grid->column('is_default', '是否默认')->display(function () {
			    	return $this->is_default ? '是' : '否';
			    });
			    $grid->column('add_time', '添加时间');
			    $grid->column('edit_time', '修改时间');
		    }
	    );

	    return $content->row($gridList->render());
    }

	public function reservation(Content $content, $id, Request $request)
	{
		$data = DecoCompany::get('*', [
			'id' => $id
		]);
		$uid = $data['uid'];

		$params = $request->all();
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [
			'deco_company_uid' => $uid
		];
		$total = DecoCompanyReservation::count($condition);

		$lists = [];
		if ($total) {
			$condition['ORDER'] = ['id' => 'DESC'];
			$condition['LIMIT'] = [
				($page - 1) * $page_size,
				$page_size
			];
			$info = DecoCompanyReservation::select('*', $condition);
			$user_ids = array_column($info, 'uid');
			$member_info = Member::getUsers($user_ids);
			foreach ($info as $item) {
				$row = [];
				$row['uid'] = $item['uid'];
				$row['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
				$row['phone'] = $item['hidden_user_phone'];
				$row['type_text'] = DecoCompanyReservation::RESERVATION_TYPE[$item['type']];
				$row['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
				$row['virtual_phone'] = $item['virtual_phone'];
				$row['virtual_expire_time'] = $item['virtual_expire_time'];
				$lists[] = $row;
			}
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => self::PAGE_SIZE
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();
				$grid->disableActions();
				$grid->disableFilter();

				$grid->column('uid', '用户UID');
				$grid->column('nick', '用户昵称');
				$grid->column('virtual_phone','虚拟手机号码')->display(function () {
                    if ((strtotime($this->add_time)) <= sReservation::DISPLAY_PHONE_TIMELINE) {
                        return '- -';
                    }else{
                        if (empty($this->virtual_phone)){
                            return "装修公司未查看";
                        }else{
                            return $this->virtual_phone;
                        }
                    }
                });
				$grid->column('virtual_expire_time','虚拟号码有效期截止至')->display(function () {
                   if ((strtotime($this->add_time)) <= sReservation::DISPLAY_PHONE_TIMELINE){
                        return '- -';
                   }else{
                       return $this->virtual_expire_time;
                   }

                });
				$grid->column('phone', '用户电话');
				$grid->column('type_text', '预约项目');
				$grid->column('add_time', '留咨日期');
			}
		);

		return $content->row($gridList->render());
	}

	public function shops(Content $content, $id)
	{
		$data = DecoCompany::get('*', [
			'id' => $id
		]);
		$uid = $data['uid'];
		$shops = Shop::getShopListByUid($uid);
		$total = empty($shops) ? 0 : count($shops);

		$gridModel = new pGridDataModel($shops, $total, [
			'perPage' => self::PAGE_SIZE
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableRowSelector();
				$grid->disableExport();
				$grid->disableCreateButton();
				$grid->disableActions();
				$grid->disableFilter();

				$grid->column('id', 'ID');
				$grid->column('name', '线下店名称');
				$grid->column('show_address', '线下店地址');
				$grid->column('format_opening_hours', '营业时间')->display(function () {
					$format_opening_hours = $this->format_opening_hours;
					$str = '';
					foreach ($format_opening_hours as $time) {
						$str .= '周'. $time['week_start'] . '&nbsp; ~ &nbsp;周' .
							$time['week_end'] . '（'. $time['time_start'] . '&nbsp; - &nbsp;'. $time['time_end'] . '）<br/>';
					}
					return $str;
				});
                $grid->column('background_pic', '背景图')->display(function () {
                    return "<img width='160' height='90' src='{$this->background_pic['pic_url']}'>";
                });
				$grid->column('add_time', '添加时间')->display(function () {
					return empty($this->add_time) ?  '-' : date('Y-m-d H:i:s', $this->add_time);
				});
				$grid->column('edit_time', '修改时间')->display(function () {
					return empty($this->edit_time) ? '-' : date('Y-m-d H:i:s', $this->edit_time);
				});
			}
		);

		return $content->row($gridList->render());
	}

	/**
	 * 中装协五星认证
	 * @param $id
	 * @return string
	 */
	public function cbda5S(Content $content, $id)
	{
		$data = DecoCompany::get('*', [
			'id' => $id
		]);
		$uid = $data['uid'];
		$certificate = Certificate::getCertificateByUid($uid);
		$data['certificate_pic'] = empty($certificate['certificate_pic']) ? self::DEFAULT_IMG :
			ImgUrl::getBauthWaterUrl(ImgUrl::APPTYPE_BAUTH, $certificate['certificate_pic'], ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG);
		$data['audit_status'] = $certificate['audit_status'];
		$data['remark'] = $certificate['remark'];

		$form = new Form($data);
		$form->hidden('id');
		$form->hidden('uid');
		$states = [
			'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
			'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
		];
		$form->switch('is_cbda_5s', '是否中装协五星认证公司')->states($states);
//		$form->imgUpload('certificate_pic', '中装协认证证书', false, [
//			'imgType' => ImgUrl::APPTYPE_BAUTH,
//			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
//		])->setWidth(4, 2);
		$form->display('certificate_pic', '中装协认证证书')->with(function ($value) {
			return "<a href='$value' target='_blank'><img src='" . $value . "' width='580' height='580'></a>";
		})->setWidth(5, 2);

		$auth_options = self::AUDIT_TEXT;
		if (!in_array($data['audit_status'], [DecoCompanyCertificate::AUDIT_PASS, DecoCompanyCertificate::AUDIT_FAIL])) {
			$auth_options[$data['audit_status']] = DecoCompanyCertificate::AUDIT_TEXT[$data['audit_status']];
		}
		$form->select('audit_status', '审核状态')->setWidth(2, 2)->options($auth_options)
//			->when(DecoCompanyCertificate::AUDIT_FAIL, function ($form) {
//				$form->select('reason', '审核未通过理由')->setWidth(3, 2)->options(self::AUDIT_FAIL_REASON);
//			})
			->required('必须选择');
		$form->textarea('remark', '备注')->setWidth(4,2);
		$form->disableReset();

		$form->confirm('确认提交吗？');

		$form->action('/admin/DecoCompany/certificate/save');
		return $content->row($form->render());
	}

	public function certificateSave(Request $request)
	{
		$params = $request->all();

//		if ($params['audit_status'] == DecoCompanyCertificate::AUDIT_FAIL && empty($params['reason'])) {
//			$error = new MessageBag([
//				'title' => '请选择审核不通过的理由'
//			]);
//			return back()->withInput()->with(compact('error'));
//		}

		// 检查证书是否上传
		$info = DecoCompanyCertificate::get('*', [
			'uid' => $params['uid'],
			'data_status' => DecoCompanyCertificate::STATUS_NORMAL
		]);

		if (empty($info['certificate_pic'])) {
			$error = new MessageBag([
				'title' => '用户未上传证书'
			]);
			return back()->withInput()->with(compact('error'));
		}

		$res = Certificate::audit([
			'uid' => $params['uid'],
			'audit_status' => $params['audit_status'],
			'reason' => $params['reason'] ?? '',
			'remark' => $params['remark'],
			'admin_id' => Admin::user()->id,
		]);

		if ($res) {
			$success = new MessageBag([
				'title' => '修改成功'
			]);
			return redirect("/admin/DecoCompany/companies/{$params['id']}/5")->with(compact('success'));
		} else {
			$error = new MessageBag([
				'title' => '修改失败'
			]);
			return back()->withInput()->with(compact('error'));
		}
	}

	public function saveBasic(Request $request)
	{
		$params = $request->all();
		$result = DecoCompany::updateInfoById($params['id'], [
			'is_show' => $params['is_show'] == 'on'? 1: 0,
		]);

		if ($result) {
			$success = new MessageBag([
				'title' => '修改成功'
			]);
			return redirect("/admin/DecoCompany/companies/{$params['id']}/1")->with(compact('success'));
		} else {
			$error = new MessageBag([
				'title' => '修改失败'
			]);
			return back()->withInput()->with(compact('error'));
		}
	}

    public function gridEdit(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $edit_data = [];
            if (isset($params['recommend_reason'])) {
                $edit_data['recommend_reason'] = $params['recommend_reason'];
            }

            if (!empty($params['sort'])) {
                $edit_data['sort'] = $params['sort'];
                // sort同步到es
                $uid = DecoCompany::get('uid', ['id' => $params['id']]);
                if (empty($uid)) {
                    throw new \Exception('uid empty');
                }
                $es_res = Schedule::saveData($uid, ['sort' => $edit_data['sort']]);
                if (!$es_res) {
                    throw new \Exception('同步es失败');
                }
            }

            if (empty($edit_data)) {
                throw new \Exception('params error');
            }

            $m_res = DecoCompany::updateInfoById($params['id'], $edit_data);
            if ($m_res === false) {
                throw new \Exception('数据库异常');
            }

            return response()->json([
                'status' => true,
                'message' => "保存成功",
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    public function groupList(Content $content, $id)
    {
        $script = <<<SCRIPT
            $('.del-btn').on('click',function(e){
                e.preventDefault();
                var id = $(this).attr('data-id');
                var d_uid = $(this).attr('data-d-uid');
                var nick = $(this).attr('data-nick');
                layer.confirm('确定将 <strong>' + nick + '</strong>，UID <strong>' + d_uid + '</strong> 从分公司移除？', {
                    btn: ['确定', '取消']
                }, function (index) {
                    layer.close(index);
                    $.ajax({
                       type: "DELETE",
                       url: "/admin/DecoCompany/companies/del_group",
                       data: "id="+id,
                       success: function(data){
                         layer.msg(data.message);
                         if (data.status) {
                            setTimeout(function () {
                               parent.window.location.reload();
                            }, 200);
                         }
                       }
                    });
                });
            });
SCRIPT;
        Admin::script($script);

        $info = DecoCompany::get('*', [
            'id' => $id
        ]);
        $headers = ['ID', 'UID', '集团公司昵称', '服务城市', '操作时间', '操作人'];
        $rows = [sDecoCompanyGroup::getGroupInfo($info['uid'])];
        $table = new Table($headers, $rows);
        $content->row((new Box('集团公司信息', $table))->solid()->style('primary'));

        $lists = sDecoCompanyGroup::getSubsidiaryList($info['uid']);
        $gridModel = new pGridDataModel($lists);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableRowSelector();

                $grid->tools(function (Grid\Tools $tools) {
                    $tools->append(new AddSubsidiary());
                });

                $grid->column('deco_id', 'ID');
                $grid->column('d_uid', 'UID');
                $grid->column('nick', '公司昵称')->display(function(){
                    return mMember::getNickByUid($this->d_uid);
                });
                $grid->column('main_area_name', '服务城市');
                $grid->column('g_uid', '归属公司')->display(function () {
                    return mMember::getNickByUid($this->g_uid);
                });
                $grid->column('add_time', '操作时间')->display(function() {
                    return date('Y-m-d H:i:s', $this->add_time);
                });;
                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
                $grid->actions(function(Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableEdit();
                    $actions->disableDelete();

                    $nick = mMember::getNickByUid($actions->row->d_uid);
                    $actions->append('<a href="javascript:void(0);" class="del-btn" data-id="' . $actions->row->id . '" data-d-uid="' . $actions->row->d_uid . '" data-nick="' . $nick . '"><i class="fa fa-trash"></i> 移除</a>');
                });
            }
        );
        $content->row((new Box('分公司管理', $gridList->render()))->solid()->style('info'));

        return $content;
    }

    public function delGroup(Request $request)
    {
        $id = $request->all('id');
        $res = sDecoCompanyGroup::deleteGroupInfo($id);
        if ($res) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function scoreEdit(Request $request) {
        $uid = $request->post('uid');
        $customScore = $request->post('custom_score');
        if (!ParamsCheck::isPositiveNumber($customScore) || $customScore < 0) {
            return response()->json([
                'status' => false,
                'message' => '分数必须为大于0的整数～'
            ]);
        }
        $info = DecoCompany::getByUid($uid);
        if (empty($info)) {
            return response()->json([
                'status' => false,
                'message' => '该装修公司不存在～'
            ]);
        }
        // 更新运营自定义分数时，同时更新用于es的排序score值
        if ($customScore == $info['custom_score']) {
            return response()->json([
                'status' => true,
                'message' => '分数未变化，无需修改～',
            ]);
        }
        if (!DecoCompany::updateInfoByUid($uid, ['score' => $customScore + $info['system_score'], 'custom_score' => $customScore])) {
            return response()->json([
                'status' => true,
                'message' => '自定义分数修改失败～',
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => '运营自定义分数修改成功～',
            'data' => []
        ]);
    }
}
